package cn.xshi.actuator.jvm;
import cn.xshi.actuator.model.JStack;
import cn.xshi.actuator.util.ExecuteCmd;
import cn.xshi.actuator.util.ActuatorSDKUtil;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @Desc 堆快照
 * @Author 邓纯杰
 * @CreateTime 2013-10-05 17:15:42
 */
public class JStackUtil {
    private final static String prefix = "java.lang.Thread.State: ";

    /**
     * 该进程的线程信息
     * X轴为时间，Y轴为值的变化
     * @return
     */
    public static JStack jstack() {
        String id = ActuatorSDKUtil.getPid();
        String s = ExecuteCmd.execute(new String[]{"jstack",id });
        int total= ActuatorSDKUtil.appearNumber(s, "nid=");
        int RUNNABLE = ActuatorSDKUtil.appearNumber(s, prefix+"RUNNABLE");
        int TIMED_WAITING = ActuatorSDKUtil.appearNumber(s,prefix+"TIMED_WAITING");
        int WAITING = ActuatorSDKUtil.appearNumber(s,prefix+"WAITING");
        return new JStack(id,total,RUNNABLE,TIMED_WAITING,WAITING);
    }

    /**
     * 导出线程快照
     * @return
     */
    public static String dump() throws IOException {
        String id = ActuatorSDKUtil.getPid();
        String path = ActuatorSDKUtil.getRootPath("dump/"+id+"_thread.txt");
        String s = ExecuteCmd.execute(new String[]{"jstack", id});
        File file = new File(path);
        FileUtils.write(file,s, String.valueOf(Charset.forName("UTF-8")));
        return path;
    }
}
